package com.lkd.handler;


import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 自动维修工单
 */
@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class VmStatusHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;


    @Override
    public void process(String jsonMsg) throws IOException {
        //解析
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        //判断参数
        if (vmStatusContract != null
            && vmStatusContract.getStatusInfo() != null
            && vmStatusContract.getStatusInfo().size() > 0)
        {
            //遍历每台设备的状态
            List<StatusInfo> statusInfo = vmStatusContract.getStatusInfo();
            for (StatusInfo info : statusInfo) {
                //如果有设备有问题,则返归false
                if (info.isStatus() == false){
                    //根据设备编号 查询设备信息
                    VmVO vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
                    //查询工单数最少的运维人员
                    int leastUser = taskService.getLeastUser(vmInfo.getRegionId(), true);
                    //封装工单消息创建工单
                    TaskViewModel task = new TaskViewModel();
                    task.setCreateType(0);//自动工单
                    task.setInnerCode(vmStatusContract.getInnerCode());//设备编号
                    task.setDesc("自动维修工单");//备注
                    task.setUserId(leastUser);//执行人id
                    task.setProductType(VMSystem.TASK_TYPE_REPAIR);//维修工单
                    taskService.createTask(task);
                }
            }

        }


    }
}
